package cn.edu.zafu.bigdata.rwx.web;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.println("服务器启动，等待连接...");
    }

    public void startServer() throws IOException {
        try {
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端连接成功: " + clientSocket.getInetAddress().getHostAddress());

            //获取输入流和输出流
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                System.out.println("客户端发送消息: " + inputLine);
                //回复客户端消息
                out.println("服务器回复消息: " + inputLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            stopServer();
        }
    }
    public void stopServer (){
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {
        int port = 12345;
        try{
            Server server = new Server(port);
            server.startServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
